package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.request.GetCustomRequest;
import com.example.demo.response.LanxinResponse;
import com.example.demo.utils.LanXinUtils;
import com.example.demo.utils.UnirestUtil;
import com.mashape.unirest.http.exceptions.UnirestException;

@RestController
@RequestMapping("/lanxin")
public class LanXinController {

    @RequestMapping("/")
    public String hello() {
        return "HELLO WORLD!!!";
    }

    @RequestMapping("/getAccessToken")
    public String getAccessToken() throws UnirestException {
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", LanXinUtils.appid);
        map.put("secret", LanXinUtils.secret);
        String result = UnirestUtil.get(LanXinUtils.getTokenURL, map);
        JSONObject object = JSONObject.parseObject(result);
        return object.get("access_token").toString();
    }

    @RequestMapping(path = "/getCustom", method={RequestMethod.POST})
    public LanxinResponse getCustom(@RequestBody GetCustomRequest request) throws UnirestException {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", getAccessToken());
        LanxinResponse result = UnirestUtil.post(LanXinUtils.getCustomURL, map, request, LanxinResponse.class);
        System.out.println(result.toString());
        return result;
    }

    @RequestMapping("/getOrg")
    public String getOrg(String mobile, String email, String orgId) throws UnirestException {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", getAccessToken());
        map.put("mobile", mobile);
        if(email != "" && email != null){
            map.put("email", email);
        }
        if(orgId != "" && orgId != null){
            map.put("orgId", orgId);
        }
        String result = UnirestUtil.get(LanXinUtils.getOrgURL, map);
        return result;
    }

    @RequestMapping("/getOrgResult")
    public String getOrgResult(String structId, String queryType) throws UnirestException {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", getAccessToken());
        map.put("structId", structId);
        map.put("queryType", queryType);
        String result = UnirestUtil.get(LanXinUtils.getOrgResult, map);
        return result;
    }

}
